package com.wdb007.venus.svc.biz.manager;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;

@Component("ossUploadManager")
public class OssUploadManager implements InitializingBean{

	private  String endpoint = "";
    private  String accessKeyId = "";
    private  String accessKeySecret = "";
    private  String bucketName = "";
    private OSSClient  ossClient ;
    @Autowired
    private ConfigInfoManager configInfoManager;
    public OssUploadManager() {
    }
    
    public void uploadImg(File file, String key) {
    	ossClient.putObject(bucketName, key, file);
    }
    
    public void uploadUserHead(byte[] data, String key) {
    	ossClient.putObject(bucketName, key, new ByteArrayInputStream(data));
    }
    
    public void downloadImg(String key, File destination) {
    	GetObjectRequest request = new GetObjectRequest(bucketName, key);
    	ossClient.getObject(request, destination);
    }
    public static void main(String[] args) {
		
    	OssUploadManager manager = new OssUploadManager();
    	File dest = new File("tmp.png");
    	manager.downloadImg("visitor_imgs/visitor_bg.png", dest);
    	
	}

	private static void upload1() {
		File f = new File("C:\\Users\\lenovo\\Desktop\\tmp\\1510652548958900.jpeg");
    	
    	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    	bos=new ByteArrayOutputStream((int)f.length());  
        BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}  
        int buf_size=1024;  
        byte[] buffer=new byte[buf_size];  
        int len=0;  
        try {
			while(-1 != (len=in.read(buffer,0,buf_size))){  
			    bos.write(buffer,0,len);  
			}
		} catch (IOException e) {
			e.printStackTrace();
		}  
    	String key = "20171120/hello2.jpeg";
    	OssUploadManager manager = new OssUploadManager();
    	manager.uploadUserHead(bos.toByteArray(), key);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		endpoint = configInfoManager.getValue("oss_endpoint");
	    	accessKeyId = configInfoManager.getValue("oss_accessKeyId");
	    	accessKeySecret = configInfoManager.getValue("oss_accessKeySecret");
	    	bucketName = configInfoManager.getValue("oss_image_bucketName");
	    	ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}
    
}
